﻿using Decision.BusinessLayer;
using QueryStringEncryption;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using thaihua.service;

public partial class userManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindingDropdownList();
            LoadAdminUser();
        }
    }

    protected override void OnInit(EventArgs e)
    {
        InitValidation();
        base.OnInit(e);
    }

    /// <summary>
    /// Init Validate RequireField in Controll
    /// </summary>
    private void InitValidation()
    {
        Validation.ValidateRequiredField(ref popUpAddNewUser, new Control[] { txt_USERNAME, txt_PASSWORD, txt_RE_PASSWORD, txt_FNAME, txt_LNAME }, Constant.VALIDATE_GROUP_SUBMIT);
    }

    private void BindingDropdownList() 
    {
        DropDownStaticFactory.GetUserGroupLvl(ref SEARCH_USER_GROUP_LVL,true);
        DropDownStaticFactory.GetUserGroupLvl(ref ddll_USER_GROUP_LVL, false);
    }

    private void LoadAdminUser()
    {
        ListAdminUser = DCSFactory.CreateECTUserFactory().GetAll().OrderBy(x => x.USERNAME).ToList();

        GridUserADmin.DataSource = ListAdminUser;
        GridUserADmin.VirtualItemCount = ListAdminUser.Count;
        GridUserADmin.DataBind();

    }

    protected string GetStatusName(Boolean isActive) 
    {
        return isActive? "ใช้งาน" : "ระงับการใช้งาน";
    }
    protected void GridUserADmin_PageSizeChanged(object sender, Telerik.Web.UI.GridPageSizeChangedEventArgs e)
    {
        GridUserADmin.CurrentPageIndex = 0;
        GridUserADmin.DataSource = ListAdminUser;
        GridUserADmin.VirtualItemCount = ListAdminUser.Count;
        GridUserADmin.DataBind();
    }
    protected void GridUserADmin_PageIndexChanged(object sender, Telerik.Web.UI.GridPageChangedEventArgs e)
    {
        GridUserADmin.CurrentPageIndex = e.NewPageIndex;
        GridUserADmin.DataSource = ListAdminUser;
        GridUserADmin.VirtualItemCount = ListAdminUser.Count;
        GridUserADmin.DataBind();
    }

    private void OpenPopup()
    {
        Util.jsWriter(this.JSUpdate, "2342", "showDialogPopupInitially();");
    }

    private void ClosePopup()
    {
        Util.jsWriter(this.JSUpdate, "2342", "closeDialogInitially();");
    }


    public List<ECT_USER> ListAdminUser
    {
        get
        {
            return ViewState["_listAdminUser"] != null ? (List<ECT_USER>)ViewState["_listAdminUser"] : new List<ECT_USER>();
        }
        set
        {
            ViewState["_listAdminUser"] = value;
            
        }
    }
    protected void InitAddNewUser(object sender, EventArgs e)
    {
        //Clear Popup
        ResetUserPopup();

        txt_USERNAME.ReadOnly = false;
        Bt_SaveNewUser.Visible = true;
        Bt_EditUser.Visible = false;
        OpenPopup();
    }
    protected void InitEditNewUser(object sender, EventArgs e)
    {
        Bt_SaveNewUser.Visible = false;
        Bt_EditUser.Visible = true;

        int userId = int.Parse(((RadButton)sender).CommandArgument);

        //Set Init User Before Edit
        ECT_USER dto = DCSFactory.CreateECTUserFactory().GetByPrimaryKey(new ECT_USERKeys(userId));

        Util.FillInFormTo(dto, Util.GetControlFrom(popUpAddNewUser), false);

        HD_USER_ID.Value = dto.USER_ID + "";
        txt_USERNAME.ReadOnly = true;
        txt_PASSWORD.Text = Util.DecryptString(dto.PASSWORD);
        txt_RE_PASSWORD.Text = txt_PASSWORD.Text;
        cal_DATE_OF_BIRTH.SelectedDate = dto.DATE_OF_BIRTH;

        if ((bool)dto.IS_ACTIVE)
        {
            Ck_IS_ACTIVE1.Checked = true;
        }
        else 
        {
            Ck_IS_ACTIVE2.Checked = true;
        }

        if(dto.SEX==0)
        {
            ck_SEX1.Checked = true;
        }
        else
        {
            ck_SEX2.Checked = true;
        }

        OpenPopup();
    }

    //EditUser
    protected void EditUser(object sender, EventArgs e) 
    {
        //Validate password and re-password
        if (txt_PASSWORD.Text != txt_RE_PASSWORD.Text)
        {
            Util.jsAlert(this.JSUpdate, "โปรดระบุรหัสผ่านให้ตรงกัน");
            return;
        }

        //Check dupp username
        //if (DCSFactory.CreateECTUserFactory().GetAllBy(ECT_USER.ECT_USERFields.USERNAME, txt_USERNAME.Text).Count > 0)
        //{
        //    Util.jsAlert(this.JSUpdate, Constant.DUPP_USERNAME);
        //    return;
        //};

        ECT_USER dto = new ECT_USER();
        Util.FillInFormTo(dto, Util.GetControlFrom(popUpAddNewUser), true);
        dto.IS_ACTIVE = Ck_IS_ACTIVE1.Checked;
        dto.SEX = ck_SEX1.Checked ? 0 : 1;
        dto.PASSWORD = Util.EncryptString(dto.PASSWORD);

        Util.jsConsole(Page, Util.ToJSon(dto));

        Util.jsAlert(JSUpdate, DCSFactory.CreateECTUserFactory().Update(dto) ? Constant.SAVE_SUCESS : Constant.SAVE_NOT_SUCESS);

        //Clear Popup
        ReSetPopup();
        //ReSet Criteria
        ReSetCriteria();
        //Load New Data
        LoadAdminUser();
    }
    protected void SaveNewUser(object sender, EventArgs e)
    {
        //Validate password and re-password
        if(txt_PASSWORD.Text != txt_RE_PASSWORD.Text)
        {
            Util.jsAlert(this.JSUpdate, "โปรดระบุรหัสผ่านให้ตรงกัน");
            return;
        }

        //Check dupp username
        if (DCSFactory.CreateECTUserFactory().GetAllBy(ECT_USER.ECT_USERFields.USERNAME, txt_USERNAME.Text).Count > 0) 
        {
            Util.jsAlert(this.JSUpdate, Constant.DUPP_USERNAME);
            return;
        };

        ECT_USER dto = new ECT_USER();
        Util.FillInFormTo(dto, Util.GetControlFrom(popUpAddNewUser), true);
        dto.IS_ACTIVE = Ck_IS_ACTIVE1.Checked;
        dto.SEX = ck_SEX1.Checked?0:1;
        dto.PASSWORD = Util.EncryptString(dto.PASSWORD);
        //Util.jsConsole(Page, Util.ToJSon(dto));

        Util.jsAlert(JSUpdate, DCSFactory.CreateECTUserFactory().Insert(dto) ? Constant.SAVE_SUCESS : Constant.SAVE_NOT_SUCESS);

        //Clear Popup
        ReSetPopup();
        //ReSet Criteria
        ReSetCriteria();
        //Load New Data
        LoadAdminUser();
    }
    protected void Bt_Close_Click(object sender, EventArgs e)
    {
        ReSetPopup();
    }

    private void ReSetPopup() 
    {
        ResetUserPopup();
        ClosePopup();
    }

    private void ResetUserPopup()
    {
        Ck_IS_ACTIVE1.Checked = true;
        ck_SEX1.Checked = true;
        Util.ResetForm(Util.GetControlFrom(popUpAddNewUser));
    }
    protected string GetStatusUserGroupLvlName(int? groupLvl)
    {
        if(groupLvl == 0)
        {
            return "ผู้ดูและระบบ";
        }
        else if (groupLvl == 1)
        {
            return "เจ้าหน้าที่บันทึกข้อมูล";
        }
        else if (groupLvl == 3)
        {
            return "ผู้บริหาร";
        }
        else
        {
            return "นิติกร";
        }
    }
    protected void Search_Click(object sender, EventArgs e)
    {
        ListAdminUser = DCSFactory.CreateECTUserFactory().GetByCriteria(new ECT_USER {
            USERNAME = SEARCH_USERNAME.Text,USER_GROUP_LVL = int.Parse(SEARCH_USER_GROUP_LVL.SelectedValue),FNAME = SEARCH_FULLNAME.Text
        }).OrderBy(x => x.USERNAME).ToList();

        GridUserADmin.CurrentPageIndex = 0;
        GridUserADmin.DataSource = ListAdminUser;
        GridUserADmin.VirtualItemCount = ListAdminUser.Count;
        GridUserADmin.DataBind();
    }
    protected void ReSet_Click(object sender, EventArgs e)
    {
        ReSetCriteria();
        ListAdminUser = null;

        GridUserADmin.CurrentPageIndex = 0;
        GridUserADmin.DataSource = ListAdminUser;
        GridUserADmin.VirtualItemCount = 0;
        GridUserADmin.DataBind();
    }

    private void ReSetCriteria()
    {
        SEARCH_FULLNAME.Text = "";
        SEARCH_USER_GROUP_LVL.SelectedIndex = 0;
        SEARCH_USERNAME.Text = "";
    }
}